package com.aivin.popuwindowdemo.window;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aivin.popuwindowdemo.callback.IWindowCallback;
import com.aivin.popuwindowdemo.bean.MarginDecoration;
import com.aivin.popuwindowdemo.tool.MyDeviceInforHelper;
import com.aivin.popuwindowdemo.R;
import com.aivin.popuwindowdemo.callback.SelectCallBack;
import com.aivin.popuwindowdemo.adapter.PopuwindowItemAdapter;
import com.aivin.popuwindowdemo.tool.WkLogTool;
import com.aivin.popuwindowdemo.bean.BgDrawable;
import com.kyleduo.switchbutton.SwitchButton;

import org.w3c.dom.Text;

import java.util.Arrays;
import java.util.List;

public class DeviceSettingWindow extends MyBasePopuwindow {
    private Context context;
    /**
     * 弹窗展示时，背景的明暗程度
     */
    private float alpha = 0.4f;
    /**
     * 弹窗的左右 padding ，dp
     */
    private int paddWidth = 40*2;
    /**
     * 弹窗的上下padding ，dp
     */
    private int paddHeight = 90*2;

    /**
     * 横向滚动条 ，这里是实现 popowindow 内部切换 view的关键 。
     * 不建议很复杂的控件
     */
    private HorizontalScrollView scrollView;
    private IWindowCallback iWindowCallback ;
    private RecyclerView recyclerView ;
    /**
     *  rootView的宽度
     */
    private int viewWidth;
    private TextView device_timezone ;


    public DeviceSettingWindow(final Context context , IWindowCallback iWindowCallback) {
        super(context);
        this.context = context;
        this.iWindowCallback = iWindowCallback;
        this.setFocusable(true);
        this.setTouchable(true);
        ColorDrawable dw = new ColorDrawable(Color.TRANSPARENT);
        this.setBackgroundDrawable(dw);
        setThisOutTouchCancel(true);

        int screenWidth = MyDeviceInforHelper.getWidth((Activity) context) ;
        int screenHeight = MyDeviceInforHelper.getHeight((Activity) context) ;
        this.setWidth(screenWidth - dp2px(context ,paddWidth) );
        this.setHeight(screenHeight-  dp2px(context ,paddHeight) );

        viewWidth = this.getWidth() ;
        this.setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss() {
                setWindowFilter(1f , (Activity) context);
            }
        });

        View rootView = initView(context);
        this.setContentView(rootView);
    }



    @SuppressLint("ClickableViewAccessibility")
    private View initView(Context context) {
        View popuwindowRootView = LayoutInflater.from(context).inflate(R.layout.devicesetting_window_lay, null);
        scrollView = popuwindowRootView.findViewById(R.id.playerSettingScrollView);

        scrollView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 禁止用户手动滑动
                return true;
            }
        });

        View windowPage1 = popuwindowRootView.findViewById(R.id.windowPage1);
        View windowPage2 = popuwindowRootView.findViewById(R.id.windowPage2);
        View windowPage3 = popuwindowRootView.findViewById(R.id.windowPage3);
        View windowPage4= popuwindowRootView.findViewById(R.id.windowPage4);

        int mRadius =60 ;
        BgDrawable bgDrawable =new BgDrawable( mRadius, Color.parseColor("#ffffff") ,Color.parseColor("#ffffff")) ;
        windowPage1.setBackground(bgDrawable );
        windowPage2.setBackground(bgDrawable);
        windowPage3.setBackground(bgDrawable);
        windowPage4.setBackground(bgDrawable);

        int screenWidth = MyDeviceInforHelper.getWidth((Activity) context) - dp2px(context ,paddWidth);
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(screenWidth, ViewGroup.LayoutParams.MATCH_PARENT);
        windowPage1.setLayoutParams(layoutParams);
        windowPage2.setLayoutParams(layoutParams);
        windowPage3.setLayoutParams(layoutParams);
        windowPage4.setLayoutParams(layoutParams);

        windowPage2.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // 点击空白处要关闭输入框
                closeInputMethod(custom_device_name);
                return false;
            }
        });

        //
        delete_device =popuwindowRootView.findViewById(R.id.bindWx_info);
        View bindWx_info = popuwindowRootView.findViewById(R.id.delete_device);
        delete_device.setBackground(new BgDrawable( 20, Color.parseColor("#4d4d4d") ,Color.parseColor("#4d4d4d")));
        bindWx_info.setBackground(new BgDrawable( 20, Color.parseColor("#236eff") ,Color.parseColor("#5895b4")));


        SwitchButton app_push_switch = popuwindowRootView.findViewById(R.id.app_push_switch);
        app_push_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                boolean isByUser = buttonView.isPressed() ;
                if(!isByUser){
                   return;
                }
                int state = isChecked ? View.VISIBLE :View.INVISIBLE ;
                delete_device.setVisibility(state);
            }
        });

        SwitchButton wx_push_switch = popuwindowRootView.findViewById(R.id.wx_push_switch);
        wx_push_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                boolean isByUser = buttonView.isPressed() ;
                if(isByUser){
                    showPicDownView(isChecked);
                }
            }
        });

        popuwindowRootView.findViewById(R.id.page1_go_page2).setOnClickListener(onClickListener);
        popuwindowRootView.findViewById(R.id.goRecordPage).setOnClickListener(onClickListener);
        popuwindowRootView.findViewById(R.id.goCheckSomethingMove).setOnClickListener(onClickListener);
        popuwindowRootView.findViewById(R.id.goAlarmRateSet).setOnClickListener(onClickListener);
        popuwindowRootView.findViewById(R.id.page2Goback).setOnClickListener(onClickListener);
        popuwindowRootView.findViewById(R.id.page3Goback).setOnClickListener(onClickListener);
        popuwindowRootView.findViewById(R.id.page4Goback).setOnClickListener(onClickListener);
        recyclerView = popuwindowRootView.findViewById(R.id.recyclerviewOfPage3) ;
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(context) );
        recyclerView.addItemDecoration(new MarginDecoration(context));

        pageName =popuwindowRootView.findViewById(R.id.pageName) ;
        popuwindowRootView.findViewById(R.id.setok_page1).setOnClickListener(onClickListener);
        popuwindowRootView.findViewById(R.id.setok_page2).setOnClickListener(onClickListener);
        popuwindowRootView.findViewById(R.id.setok_page3).setOnClickListener(onClickListener);
        popuwindowRootView.findViewById(R.id.setok_page4).setOnClickListener(onClickListener);

        device_timezone = popuwindowRootView.findViewById(R.id.device_timezone);
        custom_device_name = popuwindowRootView.findViewById(R.id.custom_device_name);
        //custom_device_name.setSelection(custom_device_name.getText().length()); // 光标移动到末位
        custom_device_name.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if(keyCode == KeyEvent.KEYCODE_ENTER){
                    String userInput = custom_device_name.getText().toString();
                    if(TextUtils.isEmpty(userInput)){
                        return true;
                    }
                    closeInputMethod(custom_device_name);
                    userInput = userInput.trim();
                    changeDeviceName(userInput);
                    return true;
                }
                return false;
            }
        });
        custom_device_name.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                custom_device_name.setCursorVisible(true); //打开光标
            }
        });
        return popuwindowRootView;
    }

    private void closeInputMethod(EditText theEditText) {
        if(theEditText==null){
            return;
        }

        theEditText.setCursorVisible(false); //关闭光标

        InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
        boolean isOpen = imm.isActive();
        if (isOpen) {
            // imm.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);//没有显示则显示
            imm.hideSoftInputFromWindow(theEditText.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void changeDeviceName(String deviceName){
        WkLogTool.showLog("deviceName="+deviceName);
        Toast.makeText(context,"保存名字为："+ deviceName ,Toast.LENGTH_SHORT).show();
    }

    private View delete_device ;
    private TextView pageName ;
    private EditText custom_device_name ;
    private void updateRecyclerView( List<String> datas){
        PopuwindowItemAdapter adapter = new PopuwindowItemAdapter(datas, new SelectCallBack() {
            @Override
            public void setSelectedCallBack(String data) {
               WkLogTool.showLog("选中="+ data);
            }
        });
        recyclerView.setAdapter(adapter);
    }

    private void showPicDownView(boolean isChecked){
        if(isChecked){
            iWindowCallback.toCheckWxPushBind();
        }

    }

    private int currentPageIndex =-1;
    private final int PAGE_INDEX_VEDIO_RECORD = 1 ;
    private final int PAGE_INDEX_ALARMRATE = 2 ;



    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int id = v.getId();

            if(id== R.id.setok_page1 ||id== R.id.setok_page2 ||id== R.id.setok_page3 ||id== R.id.setok_page4  ){
                dismssTheWindow();
            }

            else if (id == R.id.page2Goback ||  id == R.id.page4Goback) {
                // 返回设置首页
                scrollView.scrollTo(0, 0);
            }

            else if (id == R.id.page3Goback  ) {
                if(currentPageIndex== PAGE_INDEX_VEDIO_RECORD){
                    // 返回设置首页
                    scrollView.scrollTo(0, 0);
                }else if(currentPageIndex== PAGE_INDEX_ALARMRATE){
                    // 返回 移动侦测设置页
                    scrollView.scrollTo(viewWidth*3, 0);
                }

            }


            else if (id == R.id.page1_go_page2) {
                // 进入设备设置页
                scrollView.scrollTo(viewWidth, 0);
            }

            else if(id==R.id.goRecordPage){
                // 进入录像设置页
                currentPageIndex = PAGE_INDEX_VEDIO_RECORD;
                scrollView.scrollTo(viewWidth*2, 0);
                pageName.setText("录像设置");
                List<String> datas = Arrays.asList("全天录制" ,"有人经过时录制") ;
                updateRecyclerView(datas);
            }
            else if(id==R.id.goAlarmRateSet){
                // 进入警报频率设置设置页
                currentPageIndex = PAGE_INDEX_ALARMRATE;
                scrollView.scrollTo(viewWidth*2, 0);
                pageName.setText("警报频率");
                List<String> datas = Arrays.asList("一分钟" ,"三分钟" ,"五分钟") ;
                updateRecyclerView(datas);
            }

            else if(id==R.id.goCheckSomethingMove){
                // 进入 移动侦测设置页
                scrollView.scrollTo(viewWidth*3, 0);
                List<String> datas = Arrays.asList("全天录制" ,"有人经过时录制") ;
                updateRecyclerView(datas);
            }
        }
    };


    @Override
    public void showAtLocation(View parent, int gravity, int x, int y) {
        setWindowFilter(alpha , (Activity) context);
        super.showAtLocation(parent, gravity, x, y);
    }

    // region 对外的接口 - 用来更新弹窗的数据

    public void updateDeviceTimeZone(String timezone){
        if(device_timezone ==null){
            return;
        }
        device_timezone.setText(timezone);
    }

    // endregion

}
